downloadVariantJsonsHttps
- ๐ฌ๐ง English
- ๐ฎ๐น Italian
Function Name: downloadVariantJsonsHttp
Trigger: HTTPS (onRequest)
Purpose: Manages the download of product data and automatic generation of Excel reports for optical products from the Safilo catalog. Processes SKUs with result='Orderable', downloads JSON data and images, generates Excel reports, and automatically sends quotation request emails to administrators.
Detailed Functionalityโ
This Firebase Function performs a comprehensive data processing workflow for product catalogs:
1. CATALOG DATA RETRIEVALโ
- Receives catalog order ID from HTTP request
- Retrieves document from 'CatalogOrders' Firestore collection
- Utilizes Firebase Storage bucket 'arshades-7e18a.appspot.com'
2. SKU EXTRACTIONโ
- Filters only elements with result = 'Orderable' (regardless of isSelected value)
- Extracts SKU codes from filtered elements
- Removes duplicates to avoid multiple processing
3. BATCH PROCESSINGโ
- Processes SKUs in batches of 20 elements to optimize performance
- Each batch is processed in parallel for maximum efficiency
- Implements 200ms delay between API calls to avoid overload
4. JSON DOWNLOAD AND MANAGEMENTโ
- NEW API:
https://commportal-api.safilo.com/damAPI/damitems/AUTH.../spaarkly.getModels?sizeCode={sku} - Checks existence in Storage:
ARS_Library_Product_Data/{skuCode}/json/{skuCode}.json - If not exists: downloads, saves temporarily, uploads to Storage with UUID token
- If exists: uses existing file to extract image parameters
5. IMAGE DOWNLOAD AND OPTIMIZATIONโ
- Extracts modelCode, colorCode, lensCode from JSON for each SKU
- Downloads 2 images (detail=00 frontal, detail=04 lateral)
- API:
https://safilo-pd-cdn002.safilo.com/damapi/damimage/public/sfcc.getimagenofb - Optimizes images: resizes to 120x120px, JPEG quality 90%, progressive format
- Fallback: Sharp โ Jimp โ original buffer
- Storage:
ARS_Library_Product_Data/{skuCode}/thumbnail/{modelCode}_{colorCode}_{lensCode}_{detail}.jpg
6. AUTOMATIC EXCEL REPORT GENERATIONโ
- Always generates Excel report automatically at the end of processing
- Includes: skuCode, Style Description, frontal image (00), lateral image (04)
- Downloads images from URLs (Firebase Storage or API) into memory
- Optimizes images with Sharp/Jimp (120x120px, JPEG 90%)
- Creates Excel with ExcelJS: 4 columns (SKU, Description, Img00, Img04)
- Cell dimensions: width 18-30 units, height 75 points
- Image positioning: tl/br coordinates for automatic fit
- Bold headers, fixed row height
- Saves Excel to Storage:
Orders/{orderId}/Orders-orderid-report.xlsx - Generates UUID token for public access
7. API ERROR HANDLINGโ
- Detects errors during API calls (JSON and images)
- Updates order status from "processing_addition" to "error" on errors
- Adds "status" field with value "Failed - API json/images" to elements with result="Orderable"
- Returns status code 500 instead of 200 when API errors occur
- SPECIFIC HTTP 410 (Gone) HANDLING:
- Error 410 indicates image no longer available on Safilo server
- Not considered critical system error, only resource unavailability
- Processing continues normally for other SKUs
- Statistics distinguish between technical errors (failed) and unavailable images (unavailable)
8. AUTOMATIC QUOTATION REQUEST EMAILโ
- Automatically sends quotation request email when Excel report generated successfully
- Condition: must exist
excelResultwith valid downloadUrl, token and fileName - Sends TWO distinct emails:
- Administrator email: Template with key
13ef.8598f19fbcc5adb.k1.e8a28620-50ea-11f0-9c4e-dad70ff08860.197a19bc782 - User confirmation email: Template with key
13ef.8598f19fbcc5adb.k1.9337a850-5e23-11f0-9e15-dad70ff08860.197f8418755
- Administrator email: Template with key
- Uses sendQuotationRequestEmailHttp function for ZeptoMail sending
- Robust error handling: if email sending fails, it's logged but doesn't interrupt process
Technical Featuresโ
- TIMEOUT: 540 seconds (9 minutes) for long processing
- MEMORY: 1GiB to handle images and Excel files
- REGION: europe-central2 for optimal performance
- CORS: Enabled for frontend calls
- ERROR HANDLING: Detailed logging, robust fallbacks, response with errorDescription
- OPTIMIZATION: Parallel calls, intelligent cache, batch processing
- SECURITY: UUID tokens for controlled file access
- FORMAT: Excel XLSX with embedded images, professional layout
Storage Structureโ
ARS_Library_Product_Data/
โโโ {skuCode}/
โ โโโ json/
โ โ โโโ {skuCode}.json
โ โโโ thumbnail/
โ โโโ {modelCode}_{colorCode}_{lensCode}_00.jpg
โ โโโ {modelCode}_{colorCode}_{lensCode}_04.jpg
โโโ Orders/
โโโ {orderId}/
โโโ Orders-orderid-report.xlsx
Input (Payload):โ
{
"orderId": "xq02X2a6CEFVoQtZd5Pa"
}
Parameters:
orderId(string, required): ID of the catalog order document in the 'CatalogOrders' collection
Output (Success):โ
{
"success": true,
"message": "Processing completed: 5 new JSONs, 2 existing JSONs, 0 failed. Images: 8 new, 4 existing, 2 failed (partial only). 1 images not available on server (HTTP 410).",
"stats": {
"totalItems": 7,
"processedItems": 7,
"json": {
"new": 5,
"skipped": 2,
"failed": 0
},
"images": {
"new": 8,
"skipped": 4,
"failed": 2,
"unavailable": 1
},
"hasApiError": false,
"skusWithCriticalErrors": 0
},
"excelReport": {
"fileName": "Orders-xq02X2a6CEFVoQtZd5Pa-report.xlsx",
"downloadUrl": "https://firebasestorage.googleapis.com/v0/b/arshades-7e18a.appspot.com/o/Orders%2Fxq02X2a6CEFVoQtZd5Pa%2FOrders-xq02X2a6CEFVoQtZd5Pa-report.xlsx?alt=media&token=uuid-token",
"token": "uuid-token"
}
}
Response Properties:
success(boolean): Indicates if the operation was completed successfullymessage(string): Descriptive message of the processing resultsstats(object): Detailed statistics of processed itemstotalItems(number): Total number of SKUs to processprocessedItems(number): Number of SKUs actually processedjson(object): JSON download statistics (new, skipped, failed)images(object): Image download statistics (new, skipped, failed, unavailable)hasApiError(boolean): Indicates if there were critical API errorsskusWithCriticalErrors(number): Number of SKUs with critical errors
excelReport(object): Excel report informationfileName(string): Name of the generated Excel filedownloadUrl(string): Public URL for Excel file downloadtoken(string): UUID token for file access
This output is returned in the HTTP response (Postman, browser, curl).
Testingโ
URL (if HTTPS): http://127.0.0.1:5001/arshadesstaging/europe-central2/downloadVariantJsonsHttp
Test with Emulator:
- Start the Firebase emulator:
firebase emulators:start --only functions - Ensure you're using Node.js version 20:
nvm use 20 - Test with curl:
curl -X POST "http://127.0.0.1:5001/arshadesstaging/europe-central2/downloadVariantJsonsHttp" \
-H "Content-Type: application/json" \
-d '{"orderId": "xq02X2a6CEFVoQtZd5Pa"}'
Postman Testing:
- Method: POST
- URL: http://127.0.0.1:5001/arshadesstaging/europe-central2/downloadVariantJsonsHttp
- Headers:
- Key:
Content-Type - Value:
application/json
- Key:
- Body: raw JSON (see examples above)
Deploy Command:โ
firebase deploy --only functions:downloadVariantJsonsHttp
Production URL:โ
downloadVariantJsonsHttp: https://europe-central2-arshades-7e18a.cloudfunctions.net/downloadVariantJsonsHttp
Function Name: downloadVariantJsonsHttp
Trigger: HTTPS (onRequest)
Purpose: Gestisce il download di dati prodotto e la generazione automatica di report Excel per prodotti dal catalogo Safilo. Elabora SKU con result='Orderable', scarica dati JSON e immagini, genera report Excel e invia automaticamente email di richiesta quotazione agli amministratori.
Funzionamento Dettagliatoโ
Questa Firebase Function esegue un flusso di elaborazione dati completo per cataloghi di prodotti:
1. RECUPERO DATI CATALOGOโ
- Riceve l'ID dell'ordine del catalogo dalla richiesta HTTP
- Recupera il documento dalla collezione 'CatalogOrders' di Firestore
- Utilizza il bucket Firebase Storage 'arshades-7e18a.appspot.com'
2. ESTRAZIONE SKUโ
- Filtra solo gli elementi con result = 'Orderable' (indipendentemente dal valore di isSelected)
- Estrae i codici SKU dagli elementi filtrati
- Rimuove duplicati per evitare elaborazioni multiple
3. ELABORAZIONE BATCHโ
- Processa gli SKU in batch di 20 elementi per ottimizzare le performance
- Ogni batch viene elaborato in parallelo per massimizzare l'efficienza
- Implementa delay di 200ms tra chiamate API per evitare sovraccarico
4. DOWNLOAD E GESTIONE JSONโ
- NUOVA API:
https://commportal-api.safilo.com/damAPI/damitems/AUTH.../spaarkly.getModels?sizeCode={sku} - Verifica esistenza in Storage:
ARS_Library_Product_Data/{skuCode}/json/{skuCode}.json - Se non esiste: scarica, salva temporaneamente, carica su Storage con token UUID
- Se esiste: utilizza il file esistente per estrarre parametri immagini
5. DOWNLOAD E OTTIMIZZAZIONE IMMAGINIโ
- Estrae modelCode, colorCode, lensCode dal JSON per ogni SKU
- Scarica 2 immagini (detail=00 frontale, detail=04 laterale)
- API:
https://safilo-pd-cdn002.safilo.com/damapi/damimage/public/sfcc.getimagenofb - Ottimizza le immagini: ridimensiona a 120x120px, qualitร JPEG 90%, formato progressivo
- Fallback: Sharp โ Jimp โ buffer originale
- Storage:
ARS_Library_Product_Data/{skuCode}/thumbnail/{modelCode}_{colorCode}_{lensCode}_{detail}.jpg
6. GENERAZIONE REPORT EXCEL AUTOMATICAโ
- Genera SEMPRE automaticamente il report Excel alla fine dell'elaborazione
- Include: skuCode, Style Description, immagine frontale (00), immagine laterale (04)
- Scarica immagini dalle URL (Firebase Storage o API) in memoria
- Ottimizza immagini con Sharp/Jimp (120x120px, JPEG 90%)
- Crea Excel con ExcelJS: 4 colonne (SKU, Description, Img00, Img04)
- Dimensioni celle: larghezza 18-30 unitร , altezza 75 punti
- Posizionamento immagini: coordinate tl/br per fit automatico
- Intestazioni in grassetto, righe con altezza fissa
- Salva Excel su Storage:
Orders/{orderId}/Orders-orderid-report.xlsx - Genera token UUID per accesso pubblico
7. GESTIONE ERRORI APIโ
- Rileva errori durante le chiamate API (JSON e immagini)
- Aggiorna lo stato dell'ordine da "processing_addition" a "error" in caso di errori
- Aggiunge il campo "status" con valore "Failed - API json/images" agli elementi con result="Orderable"
- Restituisce status code 500 invece di 200 quando ci sono errori API
- GESTIONE SPECIFICA HTTP 410 (Gone):
- L'errore 410 indica che l'immagine non รจ piรน disponibile sul server Safilo
- Non viene considerato un errore critico del sistema, ma solo un'indisponibilitร della risorsa
- Il processamento continua normalmente per gli altri SKU
- Le statistiche distinguono tra errori tecnici (failed) e immagini non disponibili (unavailable)
8. INVIO AUTOMATICO EMAIL DI RICHIESTA QUOTAZIONEโ
- Invia automaticamente email di richiesta quotazione quando il report Excel viene generato con successo
- Condizione: deve esistere
excelResultcon downloadUrl, token e fileName validi - Invia DUE email distinte:
- Email amministratori: Template con chiave
13ef.8598f19fbcc5adb.k1.e8a28620-50ea-11f0-9c4e-dad70ff08860.197a19bc782 - Email conferma utente: Template con chiave
13ef.8598f19fbcc5adb.k1.9337a850-5e23-11f0-9e15-dad70ff08860.197f8418755
- Email amministratori: Template con chiave
- Utilizza la funzione sendQuotationRequestEmailHttp per l'invio tramite ZeptoMail
- Gestione errori robusta: se l'invio email fallisce, viene loggato ma non interrompe il processo
Caratteristiche Tecnicheโ
- TIMEOUT: 540 secondi (9 minuti) per elaborazioni lunghe
- MEMORIA: 1GiB per gestire immagini e file Excel
- REGIONE: europe-central2 per performance ottimali
- CORS: Abilitato per chiamate da frontend
- GESTIONE ERRORI: Logging dettagliato, fallback robusti, risposta con errorDescription
- OTTIMIZZAZIONE: Chiamate parallele, cache intelligente, batch processing
- SICUREZZA: Token UUID per accesso controllato ai file
- FORMATO: Excel XLSX con immagini embedded, layout professionale
Struttura Storageโ
ARS_Library_Product_Data/
โโโ {skuCode}/
โ โโโ json/
โ โ โโโ {skuCode}.json
โ โโโ thumbnail/
โ โโโ {modelCode}_{colorCode}_{lensCode}_00.jpg
โ โโโ {modelCode}_{colorCode}_{lensCode}_04.jpg
โโโ Orders/
โโโ {orderId}/
โโโ Orders-orderid-report.xlsx
Input (Payload):โ
{
"orderId": "xq02X2a6CEFVoQtZd5Pa"
}
Parametri:
orderId(string, richiesto): ID del documento dell'ordine catalogo nella collezione 'CatalogOrders'
Output (Success):โ
{
"success": true,
"message": "Elaborazione completata: 5 nuovi JSON, 2 JSON esistenti, 0 falliti. Immagini: 8 nuove, 4 esistenti, 2 fallite (solo parziali). 1 immagini non piรน disponibili sul server (HTTP 410).",
"stats": {
"totalItems": 7,
"processedItems": 7,
"json": {
"new": 5,
"skipped": 2,
"failed": 0
},
"images": {
"new": 8,
"skipped": 4,
"failed": 2,
"unavailable": 1
},
"hasApiError": false,
"skusWithCriticalErrors": 0
},
"excelReport": {
"fileName": "Orders-xq02X2a6CEFVoQtZd5Pa-report.xlsx",
"downloadUrl": "https://firebasestorage.googleapis.com/v0/b/arshades-7e18a.appspot.com/o/Orders%2Fxq02X2a6CEFVoQtZd5Pa%2FOrders-xq02X2a6CEFVoQtZd5Pa-report.xlsx?alt=media&token=uuid-token",
"token": "uuid-token"
}
}
Proprietร della Risposta:
success(boolean): Indica se l'operazione รจ stata completata con successomessage(string): Messaggio descrittivo dei risultati dell'elaborazionestats(object): Statistiche dettagliate degli elementi elaboratitotalItems(number): Numero totale di SKU da elaborareprocessedItems(number): Numero di SKU effettivamente elaboratijson(object): Statistiche download JSON (nuovi, saltati, falliti)images(object): Statistiche download immagini (nuove, saltate, fallite, non disponibili)hasApiError(boolean): Indica se ci sono stati errori API criticiskusWithCriticalErrors(number): Numero di SKU con errori critici
excelReport(object): Informazioni report ExcelfileName(string): Nome del file Excel generatodownloadUrl(string): URL pubblico per il download del file Exceltoken(string): Token UUID per l'accesso al file
Questo output viene restituito nella risposta HTTP (Postman, browser, curl).
Testingโ
URL (if HTTPS): http://127.0.0.1:5001/arshadesstaging/europe-central2/downloadVariantJsonsHttp
Test con Emulatore:
- Avvia l'emulatore Firebase:
firebase emulators:start --only functions - Assicurati di usare Node.js versione 20:
nvm use 20 - Test con curl:
curl -X POST "http://127.0.0.1:5001/arshadesstaging/europe-central2/downloadVariantJsonsHttp" \
-H "Content-Type: application/json" \
-d '{"orderId": "xq02X2a6CEFVoQtZd5Pa"}'
Test con Postman:
- Metodo: POST
- URL: http://127.0.0.1:5001/arshadesstaging/europe-central2/downloadVariantJsonsHttp
- Headers:
- Key:
Content-Type - Value:
application/json
- Key:
- Body: raw JSON (vedi esempi sopra)
Deploy Command:โ
firebase deploy --only functions:downloadVariantJsonsHttp
URL di Produzione:โ
downloadVariantJsonsHttp: https://europe-central2-arshades-7e18a.cloudfunctions.net/downloadVariantJsonsHttp